/* Copyright (c) 2005 - 2016 Hewlett Packard Enterprise Development LP  -*- Java -*-*/
/* 
 *
 * Description: Example User Defined Scalar Function: Add 2 ints
 *
 * Create Date: June 1, 2013
 */


package com.vertica.JavaLibs;

import java.util.Hashtable;

import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;

import com.vertica.sdk.*;
//LDAP域验证函数
public class AuthenADInfo extends ScalarFunctionFactory
{
    @Override
	public void getPrototype(ServerInterface srvInterface,
                             ColumnTypes argTypes,
                             ColumnTypes returnType)
    {
        argTypes.addVarchar();//domainName
        argTypes.addVarchar();//svpIp
        argTypes.addInt();//svpPort
        argTypes.addVarchar();//userName
        argTypes.addVarchar();//password
        argTypes.addVarchar();//dc
        returnType.addInt();
    }

    public class AuthenAD extends ScalarFunction
    {
    	
    	public boolean authenAD(String DOMAIN_NAME, String SVR_IP,int LDAP_DEFAULT_PORT,
    			String p_CAS_User_Name, String p_CAS_User_Pswd, String paramString5) {
    		
    		String ATTRIBUTE_USER_ACCOUNT = "SAMAccountName";
    		String[] arrayOfString = { "cn", "sn", "givenName",
    				"userPrincipalName", "canonicalName", "AdsPath" };
    		String str1 = "(&(objectcategory=Person)(objectclass=user)("
    				+ ATTRIBUTE_USER_ACCOUNT + "=" + p_CAS_User_Name + "))";

    		SearchControls localSearchControls = new SearchControls();
    		localSearchControls.setReturningAttributes(arrayOfString);

    		localSearchControls.setSearchScope(2);

    		DOMAIN_NAME = DOMAIN_NAME.trim().toLowerCase();
    		String str2;
    		if ((paramString5 == null) || (paramString5.equals("")))
    			str2 = ("." + DOMAIN_NAME).replaceAll("\\.", ",DC=").substring(1);
    		else {
    			str2 = paramString5;
    		}
    		SVR_IP = SVR_IP.trim().toLowerCase();
    		if ((SVR_IP == null) || ("".equals(SVR_IP))) {
    			SVR_IP = DOMAIN_NAME;
    		}
    		Hashtable localHashtable = new Hashtable();
    		localHashtable.put("java.naming.factory.initial",
    				"com.sun.jndi.ldap.LdapCtxFactory");

    		localHashtable.put("java.naming.provider.url", "LDAP://" + SVR_IP + ":"
    				+ String.valueOf(LDAP_DEFAULT_PORT));
    		localHashtable.put("java.naming.security.authentication", "simple");
    		localHashtable.put("java.naming.security.principal", p_CAS_User_Name
    				+ "@" + DOMAIN_NAME);
    		localHashtable.put("java.naming.security.credentials", p_CAS_User_Pswd);

    		InitialLdapContext localInitialLdapContext = null;
    		try {
    			localInitialLdapContext = new InitialLdapContext(localHashtable,
    					null);

    			NamingEnumeration localNamingEnumeration = localInitialLdapContext
    					.search(str2, str1, localSearchControls);
    			if (localNamingEnumeration.hasMoreElements()) {
    				SearchResult localSearchResult = (SearchResult) localNamingEnumeration
    						.next();
    				if (localSearchResult != null)
    					 localSearchResult.getAttributes();

    			}

    			return true;
    		} catch (Exception e) {
    			return false;
    		}

    	}
        @Override
        public void processBlock(ServerInterface srvInterface,
                                 BlockReader arg_reader,
                                 BlockWriter res_writer)
                    throws UdfException, DestroyInvocation
        {
            do {
                
                String domainName =arg_reader.getString(0);
                String svpIp =arg_reader.getString(1);
                int svpPort =Long.valueOf( arg_reader.getLong(2) ).intValue();
                String userName =arg_reader.getString(3);
                String password =arg_reader.getString(4);
                String dc =arg_reader.getString(5);
                
                boolean result =this.authenAD(domainName,  svpIp,svpPort, userName, password, dc);
                if(result){
                   res_writer.setLong(1L);
                } else {
                   res_writer.setLong(0L);	
                }
		        res_writer.next();
            } while (arg_reader.next());
        }
    }

    @Override
	public ScalarFunction createScalarFunction(ServerInterface srvInterface)
    {
        return new AuthenAD();
    }
}
